/*============================================================================================================*/
/*
	@author 
		by hariprakash
	@description 
		jQuery Multiple Carousel scripting
	@License
		Copyright (c) 2012 Hari Prakash
 		Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 	@Depends
 		jQuery
*/
/*============================================================================================================*/
(function($){
    // **********************************
    // ***** Start: Private Members *****
	'use strict';
    var pluginName = 'carouselSlider',
		settings = {
			//Variables
			imgPath : './img/',
			imgOffset : 0,
			carouselPosition : 0,
			carouselWidth : 0,
			touchXPos : 0,
			currentXPos : 0,
			touchYPos : 0,
			currentYPos : 0,
			//Elements
			$preLoader :  '.preLoader',
			$imageGallery :  '.imageGallery',
			$imageGalleryCont :  '.imageGallery .container',
			$indicator : '.cursor li',
			//States
			isCarouselLoaded : false,
			isImagesLoaded : true
		};
    // ***** Finish: Private Members *****
    // ********************************

    // *********************************
    // ***** Start: Public Methods *****
    var methods = {
        loadCarousel :function(Plugin){
			//variables
			var indicatorUI = "",
			options = Plugin.options,
			element = $(Plugin.element),
			elementWidth = element.width(),
			carouselLength = options.images.length,
			i,
			//Build UI
			imageGalleryUI = "<div class='imageGallery'><div class='container' style='width:"+elementWidth+"px;'></div></div>",
			preLoaderUI = $('<div/>',{
				'class':'preLoader'
			});
			options.carouselWidth = elementWidth;
			//Build indicators
			indicatorUI += "<ul class='cursor'>";
			for(i=0;i<carouselLength;i++)
			{
				if(i==0)
				{
					indicatorUI += "<li class='selected'></li>";
				}
				else{
					indicatorUI += "<li></li>";
				}
			}
			indicatorUI += "</ul>";
			element
				.append(imageGalleryUI,preLoaderUI,indicatorUI)
				.find(options.$imageGalleryCont)
				.append(
					$('<img/>',{
						'src':'./img/blank.gif',
						'title':'',
						'alt':''
					})
					.load(function() { 
						element.find(options.$preLoader).hide();
					})
					.attr("src",options.imgPath+options.images[0])
				)
			;
		},
		attachEvents : function(Plugin){
			var options = Plugin.options,
			element = $(Plugin.element);
			element.find(options.$indicator).on("click", function(e){
				if(!$(this).attr("class")){
					methods.changeImage(e, Plugin);
				}
			});
			element.find("img").live("touchstart", function(e){
				methods.slideTouchStart(e, Plugin);
			});
			element.find("img").live("touchmove", function(e){
				methods.slideTouchMove(e, Plugin);
			});
			element.find("img").live("touchend", function(e){
				methods.slideTouchEnd(e, Plugin);
			});
			// Listen for orientation changes
			window.addEventListener("orientationchange", function(e) {
				setTimeout(function(){
					methods.changeOrientation(e, Plugin);
				},1000);
			}, false);
		},
		changeImage : function(e, Plugin){
			e.preventDefault();
			var $target = $(e.currentTarget),
			indicator = $target.index(),
			options = Plugin.options,
			parentId = $target.parent().parent().attr("id"),
			preLoader = $("#"+parentId).find(options.$preLoader),
			image,
			imagesUI="";
			if(options.isImagesLoaded){
				preLoader.show();
			}
			options.imgOffset = 0;
			options.imgOffset = -(options.carouselWidth + 16)*indicator;
			$("#"+parentId+" .imageGallery").animate({
				left: options.imgOffset
			}, 1000, function() {
				if(options.isImagesLoaded){
					for(image in options.images){
						if(image > 0)
						{
							imagesUI += "<div class='container' style='width:"+options.carouselWidth+"px;'><img src='"+options.imgPath+options.images[image]+"' title='' alt='' /></div>";
						}
					}
					$(this).append(imagesUI);
					options.isImagesLoaded = false;
				}
				preLoader.hide();
			});
			$("#"+parentId+" "+options.$indicator).removeClass("selected");
			$target.addClass("selected");
			options.carouselPosition = indicator;
		},
		slideTouchStart : function(e, Plugin){
			e.preventDefault();
			var pageX = e.originalEvent.touches[0].pageX,
			pageY = e.originalEvent.touches[0].pageY,
			options = Plugin.options;
			options.touchXPos = pageX;
			options.currentXPos = pageX;
			options.touchYPos = pageY;
			options.currentYPos = pageY;
		},
		slideTouchMove : function(e, Plugin){
			e.preventDefault();
			var pageX = e.originalEvent.touches[0].pageX,
			pageY = e.originalEvent.touches[0].pageY,
			options = Plugin.options;
			options.currentXPos = pageX;
			options.currentYPos = pageY;
		},
		slideTouchEnd : function(e, Plugin){
			e.preventDefault();
			var options = Plugin.options,
			element = $(Plugin.element),
			totalSlide = (element.find(options.$indicator).length) - 1,
			carouselPosition = options.carouselPosition,
			diffXpos = options.touchXPos - options.currentXPos,
			diffYpos = options.touchYPos - options.currentYPos;
			if(Math.abs(diffXpos) > 10){
				if(diffXpos < 0){
					if(carouselPosition === 0){
						carouselPosition = totalSlide;
					}
					else{
						carouselPosition--;
					}
				}
				else{
					if(carouselPosition === totalSlide){
						carouselPosition = 0;
					}
					else{
						carouselPosition++;
					}
				}
				element.find(options.$indicator+":eq("+carouselPosition+")").trigger('click');
			}
			else{
				var scrollPosition = $(window).scrollTop();
				if(diffYpos < 0){
					scrollPosition -= 100;
				}
				else{
					scrollPosition += 100;
				}
				$(window).scrollTop(scrollPosition);
			}
		},
		changeOrientation : function(e, Plugin){
			var options = Plugin.options,
			element = $(Plugin.element),
			elementWidth = element.width();
			$(options.$imageGallery).css("left",0);
			$(options.$imageGalleryCont).css("width",elementWidth);
			options.carouselWidth = elementWidth;
		} 
    };
    // ***** Finish: Public Methods *****
    // *******************************
	function Plugin( element, options ) {
		this.element = element;
        this.options = $.extend( {}, settings, options) ;
        this.init();
    }
	Plugin.prototype.init = function() {
		methods.loadCarousel(this);
		methods.attachEvents(this);
	};
	// *****************************
    // ***** Start: Supervisor *****
	$.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, 
                new Plugin( this, options ));
            }
        });
    }
	
	// ***** Finish: Supervisor *****
    // ***************************
})( jQuery );
